<template>
  <div class="users-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input
        v-model="searchForm.userName"
        placeholder="请输入用户名搜索"
        class="search-input"
        clearable
        @clear="handleSearch"
      >
        <template #append>
          <el-button @click="handleSearch">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>
    </div>

    <!-- 用户列表 -->
    <el-table
      :data="userList"
      style="width: 100%"
      v-loading="loading"
      border
      row-key="userId"
      :default-sort="{ prop: 'registerDate', order: 'descending' }"
    >
      <el-table-column type="index" label="序号" width="60" fixed />
      
      <el-table-column label="头像" width="80">
        <template #default="scope">
          <el-avatar
            :size="40"
            :src="scope.row.ossImages?.[0]?.url"
          />
        </template>
      </el-table-column>
      
      <el-table-column prop="userName" label="用户名" />
      
      <el-table-column prop="email" label="邮箱" />
      
      <el-table-column prop="role" label="角色">
        <template #default="scope">
          <el-tag :type="scope.row.role === 'teacher' ? 'success' : 'info'">
            {{ scope.row.role === 'teacher' ? '教师' : '学生' }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="注册时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.registerDate) }}
        </template>
      </el-table-column>
      
      <el-table-column label="最后登录" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.lastLoginDate) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button-group>
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="编辑用户信息"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="80px"
      >
        <el-form-item label="用户名">
          <el-input v-model="userForm.userName" disabled />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="学生" value="student" />
            <el-option label="教师" value="teacher" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="userForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="正常"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import request from '@/utils/request'

export default {
  name: 'UsersManagement',
  
  components: {
    Search
  },
  
  setup() {
    // 搜索表单
    const searchForm = ref({
      userName: ''
    })
    
    // 用户列表数据
    const userList = ref([])
    
    // 加载状态
    const loading = ref(false)
    const saveLoading = ref(false)
    
    // 对话框显示状态
    const dialogVisible = ref(false)
    
    // 表单引用
    const userFormRef = ref(null)
    
    // 用户表单数据
    const userForm = reactive({
      userId: '',
      userName: '',
      role: '',
      status: 1
    })
    
    // 表单验证规则
    const userRules = {
      role: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ]
    }
    
    // 获取用户列表
    const fetchUsers = async () => {
      loading.value = true
      try {
        const response = await request({
          url: '/userService/userController/getAllUsers',
          method: 'get',
          params: {
            userName: searchForm.value.userName
          }
        })
        
        if (response.code === 200) {
          userList.value = response.data
        } else {
          ElMessage.error('获取用户列表失败')
        }
      } catch (error) {
        ElMessage.error('获取用户列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 处理搜索
    const handleSearch = () => {
      fetchUsers()
    }
    
    // 处理编辑
    const handleEdit = (row) => {
      Object.assign(userForm, {
        userId: row.userId,
        userName: row.userName,
        role: row.role,
        status: row.status
      })
      dialogVisible.value = true
    }
    
    // 处理删除
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除用户 ${row.userName} 吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const response = await request({
            url: '/userService/userController/deleteUser',
            method: 'delete',
            params: {
              userId: row.userId
            }
          })
          
          if (response.code === 200) {
            ElMessage.success('删除成功')
            fetchUsers() // 刷新列表
          } else {
            ElMessage.error(response.message || '删除失败')
          }
        } catch (error) {
          ElMessage.error('删除失败')
        }
      }).catch(() => {
        // 取消删除，不做任何操作
      })
    }
    
    // 处理保存
    const handleSave = async () => {
      if (!userFormRef.value) return
      
      try {
        await userFormRef.value.validate()
        
        saveLoading.value = true
        const response = await request({
          url: '/userService/userController/updateUserRole',
          method: 'put',
          data: userForm
        })
        
        if (response.code === 200) {
          ElMessage.success('保存成功')
          dialogVisible.value = false
          fetchUsers() // 刷新列表
        } else {
          ElMessage.error(response.message || '保存失败')
        }
      } catch (error) {
        ElMessage.error('保存失败')
      } finally {
        saveLoading.value = false
      }
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    // 组件挂载时获取用户列表
    onMounted(() => {
      fetchUsers()
    })
    
    return {
      searchForm,
      userList,
      loading,
      saveLoading,
      dialogVisible,
      userForm,
      userFormRef,
      userRules,
      handleSearch,
      handleEdit,
      handleDelete,
      handleSave,
      formatDate
    }
  }
}
</script>

<style scoped>
.users-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-area {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.search-input {
  width: 300px;
}

.el-tag {
  text-transform: capitalize;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

:deep(.el-button-group) {
  .el-button + .el-button {
    margin-left: -1px;
  }
}
</style>